/*
 * Copyright 2019-2025 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * https://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.iiifi.kite.ribbon.rule;

import java.util.List;

import org.springframework.util.Assert;

import com.iiifi.kite.ribbon.predicate.DiscoveryEnabledPredicate;
import com.netflix.loadbalancer.*;

/**
 * ribbon 路由规则
 *
 * @author kite@iiifi.com 花朝
 */
public abstract class DiscoveryEnabledRule extends PredicateBasedRule {
    private final CompositePredicate predicate;

    public DiscoveryEnabledRule(DiscoveryEnabledPredicate discoveryEnabledPredicate) {
        Assert.notNull(discoveryEnabledPredicate, "Parameter 'discoveryEnabledPredicate' can't be null");
        this.predicate = createCompositePredicate(discoveryEnabledPredicate, new AvailabilityPredicate(this, null));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public AbstractServerPredicate getPredicate() {
        return predicate;
    }

    @Override
    public Server choose(Object key) {
        ILoadBalancer lb = getLoadBalancer();

        List<Server> allServers = lb.getAllServers();
        // 过滤服务列表
        List<Server> serverList = filterServers(allServers);
        return getPredicate().chooseRoundRobinAfterFiltering(serverList, key).orNull();
    }

    /**
     * 过滤服务
     *
     * @param serverList 服务列表
     * @return 服务列表
     */
    public abstract List<Server> filterServers(List<Server> serverList);

    private CompositePredicate createCompositePredicate(DiscoveryEnabledPredicate discoveryEnabledPredicate,
            AvailabilityPredicate availabilityPredicate) {
        CompositePredicate.Builder builder =
                CompositePredicate.withPredicates(discoveryEnabledPredicate, availabilityPredicate);
        return builder.addFallbackPredicate(new AvailabilityPredicate(new RoundRobinRule(getLoadBalancer()), null))
                .build();
    }
}
